package com.ruiysoft.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.ruiysoft.conf.mq.OrderMqConfig;
import com.ruiysoft.service.order.IOrderMQAfterOperate;
import com.ruiysoft.service.order.consts.OrderOperateTypeEnum;
import com.ruiysoft.service.order.mq.bean.OrderMQAfterOperateBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Date : 2018/11/29
 *
 * @author WenJialu
 */
@Service
public class OrderMQAfterOperateImpl implements IOrderMQAfterOperate, RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

	private final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getClass());

	@Resource
	RabbitTemplate template;


	@Override
	public void send(OrderMQAfterOperateBean msg) {
		logger.info("支付订单发送消息--{}",JSON.toJSONString(msg));
		template.convertAndSend(OrderMqConfig.ORDER_AFTER_OPERATE_EXCHANGE_NAME, OrderMqConfig.ORDER_AFTER_OPERATE_ROUTE_KEY, msg, getCorrelationData(msg.getOrderNo(), msg.getOperateType()));
	}

	@Override
	public void sendAfterPaid(String orderNo, Long payAmount, Long freight, Date paidTime, Date cashWithdrawableTime, Long shopId, Long userId, String customerOpenId) {
		send(new OrderMQAfterOperateBean()
				.setOperateType(OrderOperateTypeEnum.CUSTOMER_PAID)
				.setOrderNo(orderNo)
				.setPayAmount(payAmount)
				.setFreight(freight)
				.setPaidTime(paidTime)
				.setCashWithdrawableTime(cashWithdrawableTime)
				.setShopId(shopId)
				.setUserId(userId)
				.setCustomerOpenId(customerOpenId)
		);
	}

	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		logger.info("confirm--:correlationData:" + correlationData + ",ack:" + ack + ",cause:" + cause);
	}

	@Override
	public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
		logger.error("return--message:" + new String(message.getBody()) + ",replyCode:" + replyCode + ",replyText:" + replyText + ",exchange:" + exchange + ",routingKey:" + routingKey);
	}

	private CorrelationData getCorrelationData(String orderNo, OrderOperateTypeEnum typeEnum){
		return new CorrelationData(orderNo + typeEnum.getCode());
	}
}
